import { Component, AfterViewInit, Renderer, ElementRef } from '@angular/core';
import { Location } from '@angular/common'

import { Router } from '@angular/router';
import { JhiEventManager } from 'ng-jhipster';

import { LoginService } from 'app/core/login/login.service';
import { StateStorageService } from 'app/core/auth/state-storage.service';

@Component({
  selector: 'app-login',
  templateUrl: 'login.component.html'
})
export class LoginComponent implements AfterViewInit {

  authenticationError: boolean;
  password: string;
  rememberMe: boolean;
  username: string;
  credentials: any;

  constructor(
      private eventManager: JhiEventManager,
      private loginService: LoginService,
      private stateStorageService: StateStorageService,
      private elementRef: ElementRef,
      private renderer: Renderer,
      private router: Router,
      private location: Location
  ) {
      this.credentials = {};
  }

  ngAfterViewInit() {
      setTimeout(() => this.renderer.invokeElementMethod(this.elementRef.nativeElement.querySelector('#username'), 'focus', []), 0);
  }

  cancel() {
      this.credentials = {
          username: null,
          password: null,
          rememberMe: true
      };
      this.authenticationError = false;
      // this.activeModal.hide();
      this.location.back();
  }

  login() {
      this.loginService
          .login({
              username: this.username,
              password: this.password,
              rememberMe: this.rememberMe
          })
          .then(() => {
              this.authenticationError = false;
              if (this.router.url.endsWith('register') || /^\/activate\//.test(this.router.url) || /^\/reset\//.test(this.router.url)) {
                  this.router.navigate(['']);
              }

              this.eventManager.broadcast({
                  name: 'authenticationSuccess',
                  content: 'Sending Authentication Success'
              });

              // // previousState was set in the authExpiredInterceptor before being redirected to login modal.
              // // since login is succesful, go to stored previousState and clear previousState
              const redirect = this.stateStorageService.getUrl();
              if (redirect && !redirect.endsWith('common/login')) {
                  this.stateStorageService.storeUrl(null);
                  this.router.navigate([redirect]);
              } else {
                this.router.navigate(['']);
              }
          })
          .catch(() => {
              this.authenticationError = true;
          });
  }

  register() {
      this.router.navigate(['register']);
  }

  requestResetPassword() {
      this.router.navigate(['common', 'reset']);
  }

}
